import {StoreCreator} from "@/types/utils";
import {fetchLogin, fetchUser} from "@/services/user";
import {UserSliceState} from "@/store/types";

const initialState = {
    userInfo: null,
    token: "",
    channel: 0,
}


export const createUserSlice: StoreCreator<UserSliceState> = (set, get) => ({
    ...initialState,

    login: async (data) => {
        let res = await fetchLogin(data);
        set((state) => {
            const {session_id, channel} = res.data;
            state.token = session_id;
            state.channel = channel;
        });
        return res.data;
    },
    getUserInfo: async () => {
        let res = await fetchUser();
        set((state) => {
            state.userInfo = res.data;
        });
    },
    updateUserInfo:(user)=>{
        set((state) => {
            state.userInfo = user;
        });
    },
    changeChannel: (v) => {
        set(state => {
            state.channel = v;
        });
    },
    setToken: (newToken) => set(state => {
        state.token = newToken;
    }),
    resetUser() {
        set(initialState);
    }
})